package test;
import javax.swing.*;

import Admin.Admin;
import Admin.Rolling;
import lotterySystem.Show;
import lotterySystem.Winning;
import record.DataStorage;
import record.NumbersRecord;
import user.NumberSelection;
import user.User;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class GUI {

    private JFrame frame;
    private JButton loginButton;
    private JButton registerButton;
    private JButton rechargeButton;
    private JButton infoButton;
    private JButton playButton;
    private JButton adminButton;
    private JLabel balanceLabel;
    private User currentUser;
  	static List<String> userRecords = DataStorage.readUserRecrods();
  	static List<String> numbers ;//放已买的号
    public GUI() {
    	
        frame = new JFrame("彩票抽奖系统");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(5, 1));

        loginButton = new JButton("登录");
        registerButton = new JButton("注册");
        rechargeButton = new JButton("充值");
        playButton = new JButton("选择号码");
        infoButton=new JButton("查看号码");
        adminButton = new JButton("管理员");
        balanceLabel = new JLabel("余额：0");

        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);
        buttonPanel.add(rechargeButton);
        buttonPanel.add(playButton);
        buttonPanel.add(infoButton);
        buttonPanel.add(adminButton);

        frame.add(buttonPanel, BorderLayout.CENTER);
        frame.add(balanceLabel, BorderLayout.SOUTH);

       


        // 登录按钮点击事件
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {	 
            userRecords = DataStorage.readUserRecrods();
            String username = JOptionPane.showInputDialog("请输入用户名");
                String password = JOptionPane.showInputDialog("请输入密码");
                currentUser=DataStorage.loginUser(username, password,userRecords);
                if (currentUser != null) {
                    JOptionPane.showMessageDialog(frame, "登录成功！");
                        balanceLabel.setText("余额：" + currentUser.getBalance());
                        numbers = NumbersRecord.fileToList(currentUser.getUsername());
                        Winning.notifyFirstLogin(numbers, currentUser,userRecords,balanceLabel);
                    }else {
                        JOptionPane.showMessageDialog(frame, "登录失败！请检查用户名和密码。");
                    }
            }
            
            
        });
        
        
        // 注册按钮点击事件
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            	String username = JOptionPane.showInputDialog("请输入用户名");
                String password = JOptionPane.showInputDialog("请输入密码");
                String telnumber = JOptionPane.showInputDialog("请输入电话号码");
                int r= DataStorage.register(username, password,telnumber,userRecords);
                if (r==0) {
                	JOptionPane.showMessageDialog(frame, "该用户名已被注册，请选择其他用户名。");
                } else if (r==-1) {
                    JOptionPane.showMessageDialog(frame, "密码必须为6位，请重新输入。");

                } else if(r==1){
                    JOptionPane.showMessageDialog(frame, "注册成功！");                     
                }
              }
        });

        // 充值按钮点击事件
        rechargeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
         
            	if (currentUser == null) {
                    JOptionPane.showMessageDialog(frame, "请先登录");
                    return;
                }
                String amountStr = JOptionPane.showInputDialog("请输入充值金额");
                double amount = Double.parseDouble(amountStr);
                currentUser.recharge(currentUser, amount,userRecords);
                balanceLabel.setText("余额：" + currentUser.getBalance());
                
                JOptionPane.showMessageDialog(frame, "充值成功,当前余额为："+currentUser.getBalance());
                
            }
        });

        // 选择号码按钮点击事件
        playButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            // 实现选择号码逻辑
                if (currentUser == null) {
                    JOptionPane.showMessageDialog(frame, "请先登录");
                    return;
                }
                String numberOfBets = JOptionPane.showInputDialog("投注数：");
                int bets = Integer.parseInt(numberOfBets);
                List<String> newNumbers=new ArrayList<>();
            while(bets!=0) {
                String[] options = {"手动选号", "随机选号"};
                int choice = JOptionPane.showOptionDialog(null, "请选择选号方式", "选号",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
                        null, options, options[0]);
            
                String number =null;
                switch (choice) {
                    case 0: // 手动选号           
                        number= JOptionPane.showInputDialog("请输入号码");
                        break;
                    case 1: // 随机选号
                        number=NumberSelection.selectNumberRandomly();
                        break;
                    default:
                        break;
                }
                
                if(NumberSelection.selectNumber(currentUser, number,numbers)!=null) { 
                    newNumbers.add(number);
                    bets--;
                    balanceLabel.setText("余额：" + currentUser.getBalance());
                    if(currentUser.getBalance() < 2.0&&bets!=0) {
                        JOptionPane.showMessageDialog(null, "余额不足，请先充值");
                        break;
                    }
                }else{
                    break;
                }

                 
            }
            //把新买的彩票保存到文件里，并更新numbers列表
            NumbersRecord.addNumberstoList(numbers, newNumbers);
            NumbersRecord.saveNumbersToFile(currentUser.getUsername(), newNumbers);
            DataStorage.updateBalance(currentUser.getUsername(), currentUser.getBalance(),userRecords) ;
            }
            
        });
        
        //查看号码按钮点击事件
        infoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            	
           	 if (currentUser == null) {
                    JOptionPane.showMessageDialog(frame, "请先登录");
                    return;
                }
           	Show.displayNumbers(numbers, currentUser);
            }
            
        });
            
      
        // 管理员按钮点击事件
        adminButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            	// 弹出输入对话框，让管理员输入和密码
                String adminName = JOptionPane.showInputDialog(frame, "请输入管理员用户名：");
                String adminPassword = JOptionPane.showInputDialog(frame, "请输入管理员密码：");
       
                // 验证管理员登录
                if (Admin.validateAdmin(adminName, adminPassword)) {
                	JOptionPane.showMessageDialog(frame, "管理员登录成功！");

                    // 登录成功，弹出选择操作对话框
                	boolean set=false;
                	while(!set) {
                        String[] options = {"手动设置中奖号码", "自动设置中奖号码"};
                        int selectedOption = JOptionPane.showOptionDialog(frame, "请选择管理员操作：", "管理员操作",
                                JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);

                        String winningNumber =null;
                        switch (selectedOption) {
                            case 0: // 手动设置中奖号码
                                winningNumber = JOptionPane.showInputDialog(frame, "请输入中奖号码：");                         
                               
                                break;
                            case 1: 
                                //滚动抽奖 

                                Rolling.createJframe(userRecords);    

                                // Rolling.rolling(new Rolling.RollingCallback() {
                                //     @Override
                                //     public void onRollingFinished(String winningNumber) {
                                //     	JOptionPane.showMessageDialog(frame, "抽奖结束，中奖号码："+ winningNumber);
                                //                                        // 继续执行其他逻辑...
                                //     	Show.displayWinnerInfos(Winning.checkWinning(userRecords, winningNumber),winningNumber);
                                        
                                //     }
                                // });
                                //  SwingUtilities.invokeLater(() -> new Lottery());
                                break;
                            default:
                                break;
                        }
                        if(winningNumber!=null){
                            set=Rolling.setWinningNumber(winningNumber);
                            Show.displayWinnerInfos(Winning.checkWinning(userRecords, winningNumber),winningNumber);  
                        }else{
                            set=true;
                        }
                      
                    }
                } else {
                    JOptionPane.showMessageDialog(frame, "管理员用户名或密码错误！");
                }
            }
        });

        frame.setVisible(true);
    }

}